package com.market.cash.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.SeekBar
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.market.cash.R
import com.market.cash.databinding.CashApplyBinding
import com.market.cash.pro.ProActivity
import com.market.cash.ui.adapter.CashRootApplyDaysAdapter
import com.market.cash.ui.adapter.CashRootApplyDetailsAdapter
import com.market.cash.ui.presenter.CashRootApplyPresenter
import com.market.cash.ui.view.ICashRootApplyView
import com.market.cash.utils.CashRootBarUtil
import com.market.cash.utils.CashRootDensityUtil
import com.market.cash.utils.decoration.GridSpacingItemDecoration
import com.market.cash.utils.decoration.LinearSpacingItemDecoration
import com.market.cash.utils.dialog.CashRootGuideDialog
import com.market.cash.utils.event.CashRootEventData
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.CashRootProcessHelper
import com.market.cash.utils.helper.SharedHelper
import com.market.cash.utils.helper.TestAnalysisAddEvent
import com.market.cash.utils.permission.Permission
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/24 19:21
 * @Annotation：申请贷款
 */
class ApplyActivity: ProActivity(),ICashRootApplyView {
    lateinit var binding: CashApplyBinding
    private var presenter: CashRootApplyPresenter? = null

    //老客申请金额刻度
    private var mScale = 0
    private var mMinProcess = 0//最小值

    //选择时间
    private var daysAdapter: CashRootApplyDaysAdapter? = null
    //贷款明细
    private var detailsAdapter: CashRootApplyDetailsAdapter? = null
    //埋点备注
    var eventRemark = ""

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, ApplyActivity::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun getCashRootRootView(): View {
        binding = CashApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCashRootView() {
        binding.titleLayout.setPadding(0,CashRootBarUtil.getStatusBarHeight(),0,0)

        initCashRootRefreshLayout()
        initCashRootDaysRecyclerView()
        initCashRootDetailsRecyclerView()
    }

    override fun initCashRootListener() {
        //返回
        binding.imgBack.setOnClickListener {
            finish()
        }
        //客服
        binding.imgKefu.setOnClickListener {
            KefuActivity.start(this,eventRemark,loadPName(),loadPToken())
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_CUSTOMER,eventRemark)
        }
        binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 当进度改变时调用
                val showProcess = progress * mScale + mMinProcess
                binding.textAmount.text = "$showProcess"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 当用户开始触摸SeekBar（按下）时调用
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 当用户结束触摸SeekBar（抬手）时调用
                presenter!!.loadCashRootDetailsAction()
            }
        })
        //提交
        binding.btnSubmit.setOnClickListener {
            showCashRootLoading(isTOuchOut = false, isCancel = true)
            presenter!!.onCashRootCreateOrderAction()
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_LOAN_APPLY_SUBMIT,eventRemark)
        }
    }

    override fun initCashRootData() {
        showCashRootLoading(isTOuchOut = false, isCancel = true)
        if (presenter == null){
            presenter = CashRootApplyPresenter(this)
        }
        binding.contentLayout.visibility = View.INVISIBLE
        presenter!!.loadCashRootDetailsAction()

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /* 初始化刷新 */
    private fun initCashRootRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            presenter!!.loadCashRootDetailsAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 选择days列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initCashRootDaysRecyclerView(){
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val decoration = CashRootDensityUtil.dp2px(9f)
        binding.recyclerView.addItemDecoration(GridSpacingItemDecoration(3,decoration,false))
        val layoutManager = GridLayoutManager(getContext(),3)
        binding.recyclerView.layoutManager = layoutManager
        daysAdapter = CashRootApplyDaysAdapter(binding.recyclerView)
        daysAdapter!!.setOnItemChildClickListener { _, _, position ->
            val item = this.daysAdapter!!.getItem(position)
            if (!item.optBoolean("isEnabled",true) || item.optBoolean("isSelect",false)){
                return@setOnItemChildClickListener
            }
            for (i in 0..<daysAdapter!!.itemCount){
                val model = daysAdapter!!.getItem(i)
                model.put("isSelect",false)
                if (i == position){
                    model.put("isSelect",true)
                }
            }
            daysAdapter!!.notifyDataSetChanged()

            //刷新数据
            presenter!!.loadCashRootDetailsAction()
        }
        binding.recyclerView.adapter = daysAdapter
    }

    /**
     * 初始化明细列表
     */
    private fun initCashRootDetailsRecyclerView() {
        binding.recyclerViewDetails.setHasFixedSize(true)
        binding.recyclerViewDetails.isNestedScrollingEnabled = false
        binding.recyclerViewDetails.isFocusableInTouchMode = false //不需要焦点
        val decoration = CashRootDensityUtil.dp2px(14f)
        binding.recyclerViewDetails.addItemDecoration(LinearSpacingItemDecoration(0,0,0,decoration))
        binding.recyclerViewDetails.layoutManager = LinearLayoutManager(this)
        detailsAdapter = CashRootApplyDetailsAdapter(binding.recyclerViewDetails)
        binding.recyclerViewDetails.adapter = detailsAdapter!!
        binding.recyclerViewDetails.itemAnimator = DefaultItemAnimator()
        detailsAdapter!!.setOnItemChildClickListener{ _, childView, _ ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        }
    }

    /**
     * 获取查看的产品名称
     */
    override fun loadPName(): String {
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    override fun loadPToken(): String {
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 获取贷款金额
     */
    override fun getCashRootApplyAmount(): String {
        return binding.textAmount.text.toString()
    }

    /**
     * 获取贷款期限
     */
    override fun getCashRootApplyDays(): String {
        var days = ""
        if (daysAdapter!!.itemCount > 0){
            for (i in 0..<daysAdapter!!.itemCount){
                val item = daysAdapter!!.getItem(i)
                if (item.optBoolean("isSelect",false)){
                    days = item.optString("day")
                    break
                }
            }
        }
        return days
    }

    /**
     * 不可选择贷款额度
     */
    override fun showCashRootNotOptionalViews() {
        binding.seekBar.visibility = View.GONE
        binding.loanAmountLayout.visibility = View.GONE
    }

    /**
     * 允许选择贷款额度
     */
    override fun showCashRootOptionalViews(data: JSONObject) {
        binding.seekBar.visibility = View.VISIBLE
        binding.loanAmountLayout.visibility = View.VISIBLE

        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        mMinProcess = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()
        //颗粒度
        mScale = data.optInt("granularity")

        //设置最大值
        val maxProcess = (maxAmount.toInt() - mMinProcess) / mScale
        binding.seekBar.max = maxProcess
        //设置当前值
        val showAmount = (amount.toInt() - mMinProcess) / mScale
        binding.seekBar.progress = showAmount

        binding.textMinAmount.text = "$mMinProcess"
        binding.textMaxAmount.text = maxAmount

        //是否显示过引导指引
        val isShowGuide = SharedHelper.getCashRootSPBoolean(SharedHelper.CashRoot_SPKEY.CASHROOT_DIALOG_GUIDE_SHOW)
        if (!isShowGuide){
            binding.seekBar.progress = showAmount / 2
            binding.seekBar.post {
                val setY = binding.seekBar.y + CashRootBarUtil.getStatusBarHeight() - CashRootDensityUtil.dp2px(10f) + binding.seekBar.height / 2
                val guide = CashRootGuideDialog(this,setY,object : CashRootGuideDialog.IDialogCallback{
                    override fun onGuideDismiss() {
                        SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_DIALOG_GUIDE_SHOW,true)
                        //设置当前值
                        binding.seekBar.progress = showAmount
                    }
                })
                guide.setCancelable(false)
                guide.setCanceledOnTouchOutside(false)
                guide.show()
            }
        }
    }

    /**
     * 设置贷款期限
     */
    override fun showCashRootLoanDurationList(data: JSONObject) {
        if (daysAdapter!!.itemCount == 0){
            //默认天数
            val defaultDays = data.optString("days")
            val daysArray = data.optJSONArray("daysArray")
            val dayList = arrayListOf<JSONObject>()
            if (daysArray != null) {
                //如果daysArray中没有defaultDays，需要将defaultDays添加到daysArray列表中
                var isNeedAdd = true
                for (i in 0..<daysArray.length()){
                    if (daysArray.optString(i) == defaultDays){
                        isNeedAdd = false
                        break
                    }
                }
                if (isNeedAdd){
                    daysArray.put(0,defaultDays)
                }

                for (i in 0..<daysArray.length()){
                    val day = daysArray.optString(i)
                    val obj = JSONObject()
                    obj.put("day",day)
                    obj.put("isSelect",day == defaultDays)
                    obj.put("isEnabled",true)
                    dayList.add(obj)
                }
            } else {
                val obj = JSONObject()
                obj.put("day",defaultDays)
                obj.put("isSelect",true)
                obj.put("isEnabled",true)
                dayList.add(obj)
            }
            daysAdapter!!.data = dayList
        }
    }

    /**
     * 设置贷款明细
     */
    override fun showCashRootLoadDetailsList(data: JSONObject) {
        binding.contentLayout.visibility = View.VISIBLE
        //去掉末尾的0
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        binding.textAmount.text = amount

        //明细
        val array = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        if (array != null){
            for (i in 0..<array.length()){
                val item = array.optJSONObject(i)
                if (item.has("title") && item.optString("title") == "YES"){
                    dataList.add(item)
                }
            }
            for (i in 0..<dataList.size){
                val obj = dataList[i]
                val childArray = JSONArray()
                var isAddChild = false
                for (n in 0..<array.length()){
                    val item = array.optJSONObject(n)
                    if (obj.optString("showName") == item.optString("showName")){
                        isAddChild = true
                        continue
                    }
                    if (item.has("title") && item.optString("title") == "YES"){
                        isAddChild = false
                        continue
                    }
                    if (isAddChild){
                        childArray.put(item)
                    }
                }
                obj.put("childList",childArray)
            }
        }
        detailsAdapter!!.data = dataList
    }

    /**
     * 贷款申请成功
     */
    override fun showCashRootLoanApplySuccess() {
        //贷款申请成功 - 需要打点
        TestAnalysisAddEvent.addApplyEvent()
        //刷新产品列表
        publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PRODUCT_REFRESH))

        //是否包含SMS权限
        val permissionList = CashRootCustomConfigsHelper.getCashRootPermissionsList()
        if (permissionList.contains(Permission.READ_SMS)){
            //进入SMS权限使用说明页面
            ApplySmsDataActivity.start(this,loadPName(),loadPToken())
        } else {
            //需要校验 WhatsApp 或 SMS
            if (CashRootProcessHelper.isCheckWhatsApp() || CashRootProcessHelper.isCheckSMS()){
                VerificationActivity.start(this,loadPName(),loadPToken())
            }
        }

        Handler(Looper.myLooper()!!).postDelayed({
            finish()
        },500)
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    override fun showCashRootLoanApplyFailed() {
        hideCashRootLoading()
        finish()
    }

    override fun hideCashRootLoading() {
        super.hideCashRootLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${loadPName()} LoanApply Page"
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_LOAN_APPLY_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_LOAN_APPLY_END,eventRemark)
    }
}